package com.trumeen.immichgallery.repository

import com.trumeen.immichgallery.model.*
import com.trumeen.immichgallery.network.ImmichService
import com.trumeen.immichgallery.network.RetrofitClient
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject

class NetworkRepository @Inject constructor(
    private val apiService: ImmichService
) {

    suspend fun testServerConnection(
        serverAddress: String,
        username: String,
        password: String
    ): Result<Unit> {
        return try {
            val baseUrl = if (serverAddress.startsWith("http")) {
                serverAddress
            } else {
                "http://$serverAddress"
            }

            val testApi = RetrofitClient.createApiService(baseUrl)
            testApi.pingServer()
            Result.success(Unit)
        } catch (e: HttpException) {
            Result.failure(Exception("服务器连接失败: ${e.code()}"))
        } catch (e: IOException) {
            Result.failure(Exception("网络错误: 无法连接到服务器"))
        } catch (e: Exception) {
            Result.failure(Exception("连接失败: ${e.message}"))
        }
    }

    suspend fun login(
        serverAddress: String,
        email: String,
        password: String
    ): Result<LoginResponse> {
        return try {
            val baseUrl = if (serverAddress.startsWith("http")) {
                serverAddress
            } else {
                "http://$serverAddress"
            }

            val authApi = RetrofitClient.createApiService(baseUrl)
            val response = authApi.login(LoginRequest(email, password))

            if (response.isSuccessful) {
                val loginResponse = response.body()
                if (loginResponse != null) {
                    Result.success(loginResponse)
                } else {
                    Result.failure(Exception("登录失败: 服务器返回空数据"))
                }
            } else {
                Result.failure(Exception("登录失败: 错误代码 ${response.code()}"))
            }
        } catch (e: HttpException) {
            Result.failure(Exception("登录失败: 用户名或密码不正确"))
        } catch (e: IOException) {
            Result.failure(Exception("网络错误: 无法连接到服务器"))
        } catch (e: Exception) {
            Result.failure(Exception("登录失败: ${e.message}"))
        }
    }

    suspend fun getOnThisDayImages(dataTime: String): Result<List<MemoriesResponseItem>> {
        return try {
            val response = apiService.getOnThisDayAssets(dataTime)
            if (response.isSuccessful) {
                val data = response.body()
                if (data != null) {
                    Result.success(data)
                } else {
                    Result.failure(Exception("获取图片失败: 服务器返回空数据"))
                }
            } else {
                Result.failure(Exception("获取图片失败: 错误代码 ${response.code()}"))
            }
        } catch (e: HttpException) {
            Result.failure(Exception("获取图片失败: ${e.message ?: "服务器错误"}"))
        } catch (e: IOException) {
            Result.failure(Exception("网络错误: 无法连接到服务器"))
        } catch (e: Exception) {
            Result.failure(Exception("获取图片失败: ${e.message}"))
        }
    }

    suspend fun logout(token: String): Result<Unit> {
        return try {
            val response = apiService.logout("Bearer $token")
            if (response.isSuccessful) {
                Result.success(Unit)
            } else {
                Result.failure(Exception("登出失败: 错误代码 ${response.code()}"))
            }
        } catch (e: Exception) {
            Result.failure(Exception("登出失败: ${e.message}"))
        }
    }

    suspend fun getAllPeople(): Result<PersonResponse> {
        return try {
            val response = apiService.getAllPeople(
                page = 1,
                size = 1000,
                withHidden = false
            )
            if (response.isSuccessful) {
                val data = response.body()
                if (data != null) {
                    Result.success(data)
                } else {
                    Result.failure(Exception("获取人物列表失败: 服务器返回空数据"))
                }
            } else {
                Result.failure(Exception("获取人物列表失败: 错误代码 ${response.code()}"))
            }
        } catch (e: HttpException) {
            Result.failure(Exception("获取人物列表失败: ${e.message ?: "服务器错误"}"))
        } catch (e: IOException) {
            Result.failure(Exception("网络错误: 无法连接到服务器"))
        } catch (e: Exception) {
            Result.failure(Exception("获取人物列表失败: ${e.message}"))
        }
    }

    suspend fun getTimeBuckets(personId: String): Result<List<String>> {
        return try {
            val response = apiService.getTimeBuckets(personId)
            if (response.isSuccessful) {
                val data = response.body()
                if (data != null) {
                    Result.success(data)
                } else {
                    Result.failure(Exception("获取时间桶失败: 服务器返回空数据"))
                }
            } else {
                Result.failure(Exception("获取时间桶失败: 错误代码 ${response.code()}"))
            }
        } catch (e: HttpException) {
            Result.failure(Exception("获取时间桶失败: ${e.message ?: "服务器错误"}"))
        } catch (e: IOException) {
            Result.failure(Exception("网络错误: 无法连接到服务器"))
        } catch (e: Exception) {
            Result.failure(Exception("获取时间桶失败: ${e.message}"))
        }
    }

    suspend fun getTimeBucketAssets(personId: String, timeBucket: String): Result<List<MemoriesResponseItem>> {
        return try {
            val response = apiService.getTimeBucket(personId, timeBucket)
            if (response.isSuccessful) {
                val data = response.body()
                if (data != null) {
                    Result.success(data)
                } else {
                    Result.failure(Exception("获取时间桶图片失败: 服务器返回空数据"))
                }
            } else {
                Result.failure(Exception("获取时间桶图片失败: 错误代码 ${response.code()}"))
            }
        } catch (e: HttpException) {
            Result.failure(Exception("获取时间桶图片失败: ${e.message ?: "服务器错误"}"))
        } catch (e: IOException) {
            Result.failure(Exception("网络错误: 无法连接到服务器"))
        } catch (e: Exception) {
            Result.failure(Exception("获取时间桶图片失败: ${e.message}"))
        }
    }
}